package com.qxl.forest.business.controller;

import com.google.code.kaptcha.Constants;
import com.qxl.forest.business.persistence.dao.MenuDao;
import com.qxl.forest.business.persistence.entity.Login;
import com.qxl.forest.business.persistence.entity.Menu;
import com.qxl.forest.business.persistence.entity.ShiroUser;
import com.qxl.forest.common.util.*;
import com.qxl.forest.core.log.LogManager;
import com.qxl.forest.core.log.factory.LogTaskFactory;
import com.qxl.forest.core.shiro.ShiroKit;
import com.qxl.forest.exception.InvalidKaptchaException;
import com.qxl.forest.util.CollectionKit;
import com.qxl.forest.util.CommRes;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.qxl.forest.util.HttpKit.getIp;

/**
 * @Author: qiuxinlin
 * @Dercription: 登录控制
 * @Date: 2017/11/24
 */
@RestController
public class LoginController extends BaseController {

    @Autowired
    MenuDao menuDao;

    /**
     * 跳转到登陆页面
     *
     * @return
     */
    @GetMapping(value = "/login")
    public void login(HttpServletResponse response) throws IOException {
        if (ShiroKit.isAuthenticated() || ShiroKit.getUser() != null) {
            response.sendRedirect("http://localhost:8080/#/home");
        } else {
            response.sendRedirect("http://localhost:8080/");
        }
    }

    /**
     * 跳转到首页
     *
     * @return
     */
    @GetMapping(value = "/home")
    public void home(HttpServletResponse response) throws IOException {
        response.sendRedirect("http://localhost:8080/#/home");
    }

    /**
     * 登录
     * @param login
     * @return
     */
    @PostMapping(value = "/login")
    public CommRes login(@RequestBody Login login) {
        //验证验证码是否正确
        if (CaptchaUtil.getCaptchaOnOff()) {
            String captcha = login.getCaptcha();
            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (ToolUtil.isEmpty(captcha) || !captcha.equalsIgnoreCase(code)) {
                throw new InvalidKaptchaException();
            }
        }
        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(login.getUsername(), login.getPassword().toCharArray());
        //是否选择记住我
       if (login.getRemember()) {
            token.setRememberMe(true);
        } else {
            token.setRememberMe(false);
        }
        currentUser.login(token);
        ShiroUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("user", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());
        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), getIp()));
        ShiroKit.getSession().setAttribute("sessionFlag", true);
        return CommRes.successRes();
    }

    /**
     * 获取当前登陆用户
     *
     * @return
     */
    @GetMapping("/getLoginUser")
    public CommRes getLoginUser() {
        return CommRes.success(ShiroKit.getUser());
    }

    /**
     * 根据权限获取菜单
     *
     * @param
     * @return
     */
    @GetMapping(value = "/getMenusByRoleIds")
    public CommRes getMenusByRoleIds(Model model) {
        ShiroUser user = ShiroKit.getUser();
        //获取菜单列表
        List<Integer> roleList = ShiroKit.getUser().getRoleList();
        if (CollectionUtils.isEmpty(roleList)) {
            ShiroKit.getSubject().logout();
            return CommRes.errorRes("400", "该用户没有角色，无法登陆");
        }
        String roleids = CollectionKit.join(roleList, ",");
        List<Menu> menus = menuDao.getMenusByRoleIds(roleids);
        Map<String, Object> map;
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (Menu menu : menus) {
            if (menu.getPid() == null || menu.getPid() == 0) {//ParentId = 0 表示顶级
                map = new HashMap<String, Object>();
                map.put("id", menu.getId());
                map.put("code", menu.getCode());
                map.put("name", menu.getName());
                map.put("levels", menu.getLevels());
                map.put("pid", menu.getPid());
                map.put("url", menu.getUrl());
                map.put("isopen", menu.getIsopen());
                map.put("icon", menu.getIcon());
                ToolUtil.getSonTree(map, menus);
                result.add(map);
            }
        }
        model.addAttribute("list", result);
        model.addAttribute("account", user.getAccount());
        return CommRes.success(result);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping(value = "/logout")
    public CommRes logOut() {
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), getIp()));
        ShiroKit.getSubject().logout();
        return CommRes.successRes();
    }
}
